<template>
	<!-- app登录页 -->
	<view class="page">
		<image class="login_bg" src="/static/tabbar/loginBg.png" mode=""></image>
		<c-navBar title="登录" isTran color="#fff" type='1' isBack></c-navBar>

		<view class="main" v-if="loginPage">
			<u--form :model="form" :rules="rules" ref="uForm">
				<template v-if="loginMethod==1">
					<u-form-item prop="phone">
						<u--input placeholder="请输入账号" :customStyle="{height:'78rpx'}" color="#fff" v-model="form.phone"
							border="surround"></u--input>
					</u-form-item>
					<u-form-item prop="password">
						<u--input placeholder="请输入密码" :customStyle="{height:'78rpx'}" color="#fff"
							v-model="form.password" border="surround"></u--input>
					</u-form-item>
				</template>
				<template v-else-if="loginMethod==2">
					<u-form-item prop="phone">
						<u--input placeholder="请输入手机号" :customStyle="{height:'78rpx'}" color="#fff" v-model="form.phone"
							border="surround"></u--input>
					</u-form-item>
					<u-form-item prop="code">
						<u-input placeholder="请输入验证码" :customStyle="{height:'78rpx'}" color="#fff" v-model="form.code"
							border="surround">
							<template slot="suffix">
								<view class="getcode" v-if="codeStar">{{countDown}}秒后重新获取</view>
								<view class="getcode" v-else @click="getCode">获取验证码</view>
							</template>
						</u-input>
					</u-form-item>
				</template>
			</u--form>

			<view class="textall">
				<template v-if="loginMethod==1">
					<view class="text1" @click="loginMethod=2">验证码登录</view>
					<view class="text2" @click="$fn.jumpPage('/pages/my/pages/forgotPwdVerify')">忘记密码?</view>
				</template>
				<view class="text1" v-if="loginMethod==2" @click="loginMethod=1">账号密码登录</view>
			</view>

			<view class="btn_box" @click="loginUser">登录</view>

			<view class="no_account" @click="$refs.uForm.clearValidate(),loginPage=!loginPage">没有账号? 去注册 >></view>

			<view class="third_party_login" v-if="haveWx">———— 第三方登录 ————</view>

			<view class="wx_login" @click="vxLogin" v-if="haveWx">
				<image class="wxIcon" src="/static/tabbar/wxIcon.png" mode=""></image>
			</view>

			<view class="agreement-box">
				<view class="ag-box" @click="tabAgree">
					<image v-if="isAgree" src="/static/common/select.png" mode=""></image>
					<image v-else src="/static/common/noSelect.png" mode=""></image>
				</view>
				<view class="agreement">
					<text @click.stop="tabAgree">我已阅读并同意</text>
					<text class="primary-color" @click.stop="jumpXy(1)">《用户协议》</text>
					<text class="primary-color" @click.stop="jumpXy(2)">《隐私协议》</text>
				</view>
			</view>
		</view>

		<view class="main" v-else>
			<u--form :model="form1" :rules="rules1" ref="uForm1">
				<u-form-item prop="phone">
					<u-input placeholder="请输入手机号" :customStyle="{height:'78rpx'}" color="#fff" v-model="form1.phone"
						border="surround"></u-input>
				</u-form-item>
				<u-form-item prop="code">
					<u-input placeholder="请输入验证码" :customStyle="{height:'78rpx'}" color="#fff" v-model="form1.code"
						border="surround">
						<view slot="suffix">
							<view class="getcode" v-show="codeStar">{{countDown}}秒后重新获取</view>
							<view class="getcode" v-show="!codeStar" @click="getCode">获取验证码</view>
						</view>
					</u-input>
				</u-form-item>
				<u-form-item prop="password">
					<u-input placeholder="请输入密码" :customStyle="{height:'78rpx'}" color="#fff" v-model="form1.password"
						border="surround"></u-input>
				</u-form-item>
				<u-form-item prop="passwordTo">
					<u-input placeholder="请再次输入密码" :customStyle="{height:'78rpx'}" color="#fff"
						v-model="form1.passwordTo" border="surround"></u-input>
				</u-form-item>
			</u--form>

			<view class="btn_box reg" @click="signIn">注册</view>

			<view class="no_account" @click="$refs.uForm1.clearValidate(),loginPage=!loginPage">已有账号! 去登录 >></view>

		</view>


	</view>
</template>

<script>
	export default {
		name: "appLogin",
		data() {
			return {
				form: {
					phone: '',
					password: '',
					code: ''
				},
				rules: {
					phone: [{
						type: 'string',
						required: true,
						message: '请输入账号',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}],
					password: {
						type: 'string',
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					},
					code: {
						type: 'string',
						required: true,
						message: '请输验证码',
						trigger: ['blur', 'change']
					},
				},
				isAgree: false, //是否同意协议
				loginMethod: 1, //登录方式 1.账号密码登录 2.验证码登录
				countDown: 60, //60秒后重新获取
				timer: null, //定时器
				codeStar: false, //开始倒计时
				loginPage: true, //登录还是注册

				form1: {
					phone: '',
					password: '',
					passwordTo: '',
					code: ''
				},
				rules1: {
					phone: [{
						type: 'string',
						required: true,
						message: '请输入账号',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}],
					password: {
						type: 'string',
						required: true,
						message: '请输入密码',
						trigger: ['blur', 'change']
					},
					passwordTo: [{
						type: 'string',
						required: true,
						message: '请再次输入密码',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return this.form1.password == value
						},
						message: '两次密码不一致',
						trigger: ['change', 'blur'],
					}],
					code: {
						type: 'string',
						required: true,
						message: '请输验证码',
						trigger: ['blur', 'change']
					},
				},
				haveWx: false
			};
		},
		onLoad() {},
		onShow() {
			this.checkApp()
		},
		methods: {
			// 判断是否安装了微信
			checkApp() {

				// uni.getProvider({
				// 	service: 'share',
				// 	success: (res) => {
				// 		// console.log(res.provider,'res.provider');
				// 		if (res.provider[0] == 'weixin') {
				// 			// console.log('微信已安装');
				// 			// uni.showToast({
				// 			// 	icon: 'success',
				// 			// 	title: '微信已安装',
				// 			// 	duration: 2000
				// 			// })
				// 			this.haveWx = true
				// 		} else {
				// 			// console.log('微信未安装');
				// 			// uni.showToast({
				// 			// 	icon: 'fail',
				// 			// 	title: '微信未安装',
				// 			// 	duration: 2000
				// 			// })
				// 			this.haveWx = false
				// 		}
				// 	}
				// })

				if (plus.runtime.isApplicationExist({
						pname: 'com.tencent.mm',
						action: 'weixin://'
					})) {
					//已安装微信
					// uni.showToast({
					// 	icon: 'success',
					// 	title: '微信已安装1',
					// 	duration: 5000
					// })
					this.haveWx = true
				} else {
					//未安装微信
					// uni.showToast({
					// 	icon: 'fail',
					// 	title: '微信已未安装1',
					// 	duration: 5000
					// })
					this.haveWx = false
				}


			},



			// 获取验证码
			getCode() {

				// 模拟向后端请求验证码
				uni.showLoading({
					title: '正在获取验证码'
				})
				if (!this.form.phone && this.loginPage) {
					uni.hideLoading();
					return uni.$u.toast('请先输入手机号');
				}
				if (!this.form1.phone && !this.loginPage) {
					uni.hideLoading();
					return uni.$u.toast('请先输入手机号');
				}
				console.log(this.form.phone, '获取到手机号');
				this.$api.loginSendCode({
					phone: this.loginPage ? this.form.phone : this.form1.phone,
					type: 3
				}).then(res => {
					console.log(res, '获取到手机号');
					this.countDown = 60
					this.codeStar = true
					// 这里此提示会被this.start()方法中的提示覆盖
					uni.$u.toast('验证码已发送');
					this.timer = setInterval(() => {
						this.countDown--
						if (this.countDown == 0) {
							this.codeStar = false
							clearInterval(this.timer)
						}
					}, 1000)
				}).finally(() => {
					uni.hideLoading();
				})
			},

			codeChange(text) {
				this.tips = text;
			},
			// 登录
			async loginUser() {
				this.$refs.uForm.validate().then(res => {
					if (!this.isAgree) return uni.$u.toast('请先查看并同意协议');
					if (this.loginMethod == 1) {
						this.$api.loginAccount(this.form).then(res => {
							console.log(res, '登录成功-账号密码');
							this.loginSuccess(res)
						})
					} else if (this.loginMethod == 2) {
						console.log(this.form.code, "验证码")
						console.log(this.form.phone, "手机号")
						this.$api.loginPhone(this.form).then(res => {
							console.log(res, '登录成功-验证码');
							this.loginSuccess(res)
						})
					}
				}).catch(errors => {})
			},
			// 登录成功
			loginSuccess(res) {
				uni.$u.toast('登录成功')
				this.$u.vuex("vuex_token", res.data.accessToken);
				uni.setStorageSync("token", res.data.accessToken);
				uni.setStorageSync("userInfo", res.data.detail);
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/tabbar/home',
					});
				}, 500);
			},

			vxLogin() {
				if (!this.isAgree) return uni.$u.toast('请先查看并同意协议');
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: (event) => {
						const {
							code
						} = event
						//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
						console.log(code, 'code');
						this.$api.loginWechat({
							loginCode: code
						}).then(res => {
							console.log(res, '登录成功-微信');
							this.loginSuccess(res)
						})

					},
					fail: (err) => {
						// 登录授权失败
						// err.code是错误码
						console.log('err.code是错误码', err);
					},

				})


				// var weixinOauth = null;
				// plus.oauth.getServices((services)=> {
				// 	for (var i in services) {
				// 		var service = services[i];
				// 		// 获取微信登录对象
				// 		if (service.id == 'weixin') {
				// 			weixinOauth = service;
				// 			break;
				// 		}
				// 	}
				// 	weixinOauth.authorize((event)=> {
				// 		const {
				// 			code
				// 		} = event
				// 		//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
				// 		console.log(code,'code');
				// 		this.$api.loginWechat({
				// 			loginCode: code
				// 		}).then(res => {
				// 			console.log(res, '登录成功-微信');
				// 			this.loginSuccess(res)
				// 		})
				// 	}, function(err) {
				// 		// 登录授权失败
				// 		// err.code是错误码
				// 		console.log(err,'er2r');
				// 	})
				// }, function(err) {
				// 	// 获取 services 失败
				// 	console.log(err,'er1r');
				// })
			},

			signIn() {
				console.log('注册成功');
				this.$refs.uForm1.validate().then(res => {
					console.log('注册成功111');
					this.$api.register(this.form1).then(res => {
						console.log('注册成功', res);
						uni.$u.toast('注册成功')
						this.loginPage = true
						this.$refs.uForm1.resetFields()
					})
				}).catch(errors => {})
			},


			// 同意/不同意协议
			tabAgree() {
				this.isAgree = !this.isAgree;
			},
			// 跳转协议
			jumpXy(e) {
				uni.navigateTo({
					url: '/pages/tabbar/agreement?type=' + e
				})
			},


		}
	};
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
	}

	.login_bg {
		width: 100vw;
		height: 100%;
		position: absolute;
		z-index: -1;
	}

	.main {
		padding: 35vh 80rpx 0;
		box-sizing: border-box;

		.textall {
			font-size: 24rpx;
			margin: 12rpx 0 40rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.text1 {
				color: #01FFCC;
			}

			.text2 {
				color: #FFFFFF;
			}
		}

		.btn_box {
			width: 100%;
			height: 96rpx;
			background: #01FFCC;
			border-radius: 12rpx;
			font-weight: bold;
			font-size: 36rpx;
			color: #1A1A1A;
			line-height: 96rpx;
			text-align: center;
		}

		.reg {
			margin-top: 10%;
		}

		.no_account {
			font-size: 28rpx;
			color: #01FFCC;
			line-height: 33rpx;
			text-align: center;
			margin-top: 48rpx;
		}

		.third_party_login {
			font-weight: 400;
			font-size: 24rpx;
			color: #BBC3CC;
			line-height: 24rpx;
			text-align: center;
			margin: 15% 0 6%;
		}


		.wx_login {
			display: flex;
			justify-content: center;

			.wxIcon {
				width: 64rpx;
				height: 64rpx;
			}
		}
	}

	.agreement-box {
		position: fixed;
		bottom: 2%;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		// margin-top: 4%;

		.ag-box {
			width: 50rpx;
			height: 50rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		image {
			width: 24rpx;
			height: 24rpx;
		}

		.agreement {
			font-size: 24rpx;
			font-weight: 400;
			color: #BBC3CC;

			.primary-color {
				color: #01FFCC;
			}
		}
	}

	.getcode {
		font-size: 28rpx;
		color: #FFFFFF;
	}
</style>